using System;
using System.Collections.Generic;

namespace Tycho.Parser.Peg {
    public class LazyGrammar {
        private IDictionary<string, List<IProduction>> InheritedProductions;
        private IDictionary<string, List<IProduction>> StoredProductions;
        private LazyGrammar OuterGrammar;

        public LazyGrammar () {
            InheritedProductions = null;
            StoredProductions = null;
            OuterGrammar = null;
        }

        public LazyGrammar Push () {
            return new LazyGrammar ()
                   {InheritedProductions = StoredProductions ?? InheritedProductions, OuterGrammar = this};
        }

        public IDictionary<string, List<IProduction>> Productions {
            get {
                if (StoredProductions == null) {
                    if (InheritedProductions != null) {
                        StoredProductions = CloneProductions ();
                    } else {
                        StoredProductions = new Dictionary<string, List<IProduction>> ();
                    }
                }

                return StoredProductions;
            }
        }

        private Dictionary<string, List<IProduction>> CloneProductions () {
            var productions = new Dictionary<string, List<IProduction>> ();

            foreach (var keyValue in InheritedProductions) {
                productions.Add (keyValue.Key, new List<IProduction> (keyValue.Value));
            }

            return productions;
        }

        public LazyGrammar Pop () {
            if (OuterGrammar == null) {
                throw new InvalidOperationException ("no grammars left to pop");
            }

            return OuterGrammar;
        }
    }
}